package com.example.demo.Util;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by 汪玉东 on 2017/9/30.
 */
public class PropertiesUtil {

    public void WriteProperties(Map map){
        //InputStream is=SourceLoader.class.getClassLoader().getSystemResourceAsStream("dhhConfig.properties");
        String f=this.getClass().getResource("/").getPath()+"dhhConfig.properties";
        InputStream is= null;
        try {
            is = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            WriteProperties(is,map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //写入Properties信息
    public  void WriteProperties (InputStream is, Map map) throws IOException {
        Properties pps = new Properties();

        pps.load(is);
        pps.putAll(map);

        String f=this.getClass().getResource("/").getPath()+"dhhConfig.properties";

        pps.store(new FileWriter(f), "Update "+ " name");
        is.close();

    }





    public Properties loadConfig(){
        Properties p=new Properties();

        //InputStream is=SourceLoader.class.getClassLoader().getSystemResourceAsStream("dhhConfig.properties");
        String f=this.getClass().getResource("/").getPath()+"dhhConfig.properties";
        InputStream is= null;
        try {
            is = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return   p;
    }


    /**
           * 获取Properties所有的值
           * @author Sean
           * @date 2015-6-5
           * @return            返回Properties的键值对
           */
     public Map<String,Object> getAllProperties(Properties properties ){

                 Map<String,Object> map=new HashMap<String,Object>();
                 //获取所有的键值
                 Enumeration enumeration=properties.propertyNames();
                 while(enumeration.hasMoreElements()){
                         String key=(String) enumeration.nextElement();
                         Object value=getValueByKey(properties,key);
                         map.put(key, value);
                     }
                 return  map;
             }


    /**
     97      * 通过关键字获取值
     98      * @author Sean
     99      * @date 2015-6-5
     100      * @param key    需要获取的关键字
     101      * @return        返回对应的字符串，如果无，返回null
     102      */
     public String getValueByKey(Properties properties,String key){

                 String val =properties.getProperty(key.trim());
                 return val;

             }


}
